package com.example.p2pinvest.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.example.p2pinvest.R;
import com.example.p2pinvest.bean.UpdateInfo;
import com.example.p2pinvest.common.ActivityManager;
import com.example.p2pinvest.common.AppNetConfig;
import com.example.p2pinvest.util.UIUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;


public class WelcomeActivity extends Activity {

    private static final int TO_MAIN = 1;
    private static final int DOWNLOAD_VERSION_SUCCESS = 2;
    private static final int DOWNLOAD_APK_FAIL = 3;
    private static final int DOWNLOAD_APK_SUCCESS = 4;
    @BindView(R.id.iv_welcome_icon)
    ImageView ivWelcomeIcon;
    @BindView(R.id.rl_welcome)
    RelativeLayout rlWelcome;
    @BindView(R.id.tv_version)
    TextView tvVersion;

    private UpdateInfo info;

    private long startTime;
    private long currentTime;

    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case TO_MAIN:
                    finish();
                    startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                    break;
                case DOWNLOAD_VERSION_SUCCESS:
                    //获取当前应用的版本信息
                    String version = getVersion();
                    //更新页面版本信息
                    tvVersion.setText(version);
                    //比较服务器获取的最新版本和当前应用的版本
                    if (version.equals(info.getVersion())) {
                        UIUtils.toast("当前应用已经是最新版本", false);
                        toMain();
                    } else {
                        new AlertDialog.Builder(WelcomeActivity.this)
                                .setTitle("下载最新版本")
                                .setMessage(info.getDesc())
                                .setPositiveButton("立即下载", (dialog, which) -> {
                                    //下载服务器保存的应用数据
                                    downloadApk();
                                })
                                .setNegativeButton("暂不下载", (dialog1, which) -> {
                                    toMain();
                                })
                                .show();
                    }
                    break;
                case DOWNLOAD_APK_FAIL:
                    UIUtils.toast("联网下载数据失败", false);
                    toMain();
                    break;
                case DOWNLOAD_APK_SUCCESS:
                    UIUtils.toast("下载数据成功", false);
                    dialog.dismiss();  //下载进度条消失
                    installApk();  //安装下载好的应用
                    finish(); //结束当前的页面显示
                    break;
            }
        }
    };

    /**
     * 安装下载好的应用
     */
    private void installApk() {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", apkFile);
        } else {
            uri = Uri.parse("file://" + apkFile.getAbsolutePath());
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }

    private ProgressDialog dialog;
    private File apkFile;

    /**
     * 联网下载apk
     */
    private void downloadApk() {
        //初始化下载进度条
        dialog = new ProgressDialog(this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setCancelable(false);
        dialog.show();
        //初始化数据要保存的位置
        File fileDir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            fileDir = this.getExternalCacheDir();
        } else {
            fileDir = this.getFilesDir();
        }
        apkFile = new File(fileDir, "update.apk");

        //启动分线程联网下载数据
        new Thread(() -> {
            String askUrl = info.getApkUrl();
            InputStream is = null;
            FileOutputStream fos = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(askUrl);
                connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);

                connection.connect();

                if (connection.getResponseCode() == 200) {
                    //联网成功
                    dialog.setMax(connection.getContentLength());  //设置dialog的最大值

                    is = connection.getInputStream();
                    fos = new FileOutputStream(apkFile);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        //更新dialog的进度
                        dialog.incrementProgressBy(len);

                        fos.write(buffer, 0, len);
                    }
                    handler.sendEmptyMessage(DOWNLOAD_APK_SUCCESS);
                } else {
                    handler.sendEmptyMessage(DOWNLOAD_APK_FAIL);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();
    }

    /**
     * 获取当前版本号
     */
    private String getVersion() {
        String version = "未知版本";
        PackageManager manager = getPackageManager();
        try {
            PackageInfo packageInfo = manager.getPackageInfo(getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (Exception e) {

        }
        return version;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);

        //将当前的activity加入到activityManager中
        ActivityManager.getInstance().add(this);

        //提供启动动画
        setAnimation();

        //联网更新应用
        updateApkFile();
    }

    /**
     * 联网更新应用
     */
    private void updateApkFile() {
        //获取系统此方法开始时间
        startTime = System.currentTimeMillis();

        //判断手机是否可以联网
        boolean connect = isConnect();
        if (!connect) {
            // 没有网络
            UIUtils.toast("当前没有移动数据网络", false);
            toMain();
        } else {
            //有网络
            //联网获取服务器的最新版本数据
            AsyncHttpClient client = new AsyncHttpClient();
            client.get(AppNetConfig.UPDATE, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String response = new String(responseBody, StandardCharsets.UTF_8);
                    //获取服务器的最新版本
                    info = JSON.parseObject(response, UpdateInfo.class);
                    //比较两个版本是否相同
                    handler.sendEmptyMessage(DOWNLOAD_VERSION_SUCCESS);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    UIUtils.toast("联网请求数据失败", false);
                    toMain();
                }
            });
        }
    }

    private void toMain() {
        //获取系统当前时间
        currentTime = System.currentTimeMillis();
        //如果开启动画未结束,则等待动画结束再跳转到主界面
        long delayTime = 3000 - (currentTime - startTime);
        if (delayTime < 0) {
            delayTime = 0;  //如果动画已经结束,则即时跳转到主界面
        }
        handler.sendEmptyMessageDelayed(TO_MAIN, delayTime);
    }

    /**
     * 检查网络连接是否可用
     * @return
     */
    private boolean isConnect() {
        /*boolean connected = false;
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null) {
            connected = networkInfo.isConnected();
        }
        return connected;*/
        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if(Build.VERSION.SDK_INT>=23) {
            //获取网络属性
            NetworkCapabilities networkCapabilities = mConnectivityManager.getNetworkCapabilities(mConnectivityManager.getActiveNetwork());
            if (networkCapabilities != null) {
                return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
            }
        }else {
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isConnected();
            }
        }
        return false;
    }

    private void setAnimation() {
        AlphaAnimation animation = new AlphaAnimation(0, 1);//完全透明到完全不透明
        animation.setDuration(3000); //持续时间
        animation.setInterpolator(new AccelerateInterpolator());  //设置动画的变化率

        //启动动画
        rlWelcome.startAnimation(animation);
    }
}